<template>
  <dtDialog
    :title="textMap[dialogStatus]"
    :visible.sync="dialogFormVisible"
    :is-loading="loading"
    @closeDialog="resetTemp()"
    @comfirmBtn="onSubmit()"
  >
    <DtForm v-if="changeRadio = 1" :form-opts="config" :width-size="1"
            :ref-obj.sync="config.ref" :disabled="isDisabled">
      <template #appIcon>
        <uploadIcon ref="uploadIcon" v-model="config.formData.appIcon"  :isDisabled="isDisabled"
                    :file-type="fileType" :file-size="fileSize" :icon-color.sync="config.formData.iconColor" />
      </template>
      <template #maintainer>
        <personSelect
          ref="personPicker"
          :value="config.formData.maintainer"
          :multiple="true"
          :reappear="true"
          :select-type="'person'"
          :tag-visible="true"
          :api="api"
          :selected-data="seletList"
          @handleSelectData="selected"
          :disabled="config.columns[4].disabled"
        />
      </template>
    </DtForm>
  </dtDialog>
</template>
<script>
import uploadIcon from './uploadIcon.vue'
import { uuId } from '@/framework/utils/uuid'
import appListApi from '@/framework/api/developerCenter/application-center/applicationCenter'
import appTypeApi from '@/framework/api/developerCenter/application-center/applicationClassify'
import selectPersonApi from '@/framework/api/addPerson.js'
import { cloud } from '@/framework/utils/request'

const validateRemarkCheck = (rule, value, callback) => {
  if (!value) {
    callback(new Error('描述不能为空'))
  } else if (value.length < 35) {
    callback(new Error('输入长度至少为35'))
  } else {
    callback()
  }
}
export default {
  components: {
    uploadIcon
  },
  data() {
    return {
      loading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '设置应用',
        create: '新建应用'
      },
      fileType: [
        'png',
        'jpg',
        'jpeg'
      ],
      fileSize: 0.2,
      api: { ...selectPersonApi, ...appListApi },
      config: {
        ref: null,
        labelWidth: '120px',
        formData: {
          appId: null,
          appName: null,
          appCode: null,
          appSource: null,
          isSingleIntegration: null,
          isBaseApp: null,
          appType: '',
          appAddress: '',
          appSecret: null,
          appIcon: '',
          iconColor: '',
          openNewTag: null,
          maintainer: '',
          remark: null,
          appSort: null,
          sysAppEncry: {
            platSyPublicKey: null,
            thirdSyPrivateKey: null
          }
          // appId: '',
          // appName: '',
          // appCode: '',
          // appType: '',
          // appIcon: '',
          // iconType: '',
          // iconColor: '',
          // remark: '',
          // maintainer: '',
          // createTime: '',
          // createUser: ''
        },
        labelPosition: 'right',
        columns: [
          {
            label: '应用名称',
            prop: 'appName',
            type: 'text',
            component: 'el-input',
            maxlength: 20
          },
          {
            label: '应用编码',
            prop: 'appCode',
            type: 'text',
            component: 'el-input',
            maxlength: 20
          },
          {
            label: '应用分类',
            prop: 'appType',
            type: 'select-arr',
            list: 'typeList',
            component: 'el-select',
            arrLabel: 'typeName',
            arrKey: 'id'
          },
          {
            label: '应用图标',
            prop: 'appIcon',
            slotName: 'appIcon'
          },
          {
            label: '维护人',
            prop: 'maintainer',
            slotName: 'maintainer',
            isHideItem: true
          },
          {
            label: '描述',
            prop: 'remark',
            type: 'textarea',
            component: 'el-input',
            maxlength: 200
          },
          {
            label: '创建人',
            prop: 'createUser',
            type: 'text',
            component: 'el-input',
            isHideItem: true,
            disabled: true
          },
          {
            label: '创建时间',
            prop: 'createTime',
            type: 'text',
            component: 'el-input',
            isHideItem: true,
            disabled: true
          }
        ],
        rules: {
          appName: [
            {
              required: true,
              trigger: 'blur',
              message: '请输入应用名称'
            }
          ],
          appCode: [
            {
              required: true,
              trigger: 'blur',
              message: '请输入应用编码'
            }
          ],
          appType: [
            {
              required: true,
              trigger: 'blur',
              message: '请选择应用分类'
            }
          ],
          appIcon: [
            {
              required: true,
              trigger: 'change',
              message: '请选择应用图标'
            }
          ],
          maintainer: [
            {
              required: true,
              trigger: 'blur',
              message: '请选择维护人'
            }
          ],
          remark: [
            { required: true, validator: validateRemarkCheck, trigger: 'blur' }
          ]
        },
        listTypeInfo: {
          typeList: []
        }
      },
      seletList: [],
      isDisabled: false
    }
  },
  created() {
    this.getTypeList()
    this.config.formData = { ...this.config.formData, ...this.initForm() }
  },
  methods: {
    initForm() {
      return {
        appIcon: '',
        appSource: 1, // 应用来源
        openNewTag: 1, // 是否打开新页签
        isSingleIntegration: 1, // 是否需要单点集成
        isBaseApp: 1 // 是否基础应用
      }
    },
    // 获取应用分类数据
    getTypeList() {
      appTypeApi.sysAppTypeList().then((res) => {
        this.config.listTypeInfo.typeList = res.data
      })
    },
    // 关闭弹窗
    resetTemp() {
      this.reset()
    },
    selected(val) {
      this.config.formData.maintainer = val.map((item) => {
        return item.userId
      }).join(',')
      // this.seletCarbonUserList = val;
      this.seletList = val
    },
    // 表单重置
    reset() {
      this.config.formData = { ...{
        appId: null,
        appName: null,
        appCode: null,
        appSource: null,
        isSingleIntegration: null,
        isBaseApp: null,
        appType: '',
        appAddress: '',
        appSecret: null,
        appIcon: '',
        iconColor: '',
        openNewTag: null,
        maintainer: '',
        remark: null,
        appSort: null,
        sysAppEncry: {
          platSyPublicKey: null,
          thirdSyPrivateKey: null
        }
      },
      ...this.initForm() }
      this.$refs?.uploadIcon?.clear()
      this.seletList = []
      // this.$refs.personPicker.select = []
      this.$nextTick(() => {
        this.config.ref.clearValidate()
      })
    },
    // 打开新增弹窗
    openDialog(type, data) {
      this.dialogStatus = type
      this.dialogFormVisible = true
      this.getTypeList()
      if (type === 'update') {
        this.config.columns[1].disabled = true
        this.isDisabled = !data.editable
        // this.config.columns.map((res) => {
        //   if (res.prop !== 'createUser' && res.prop !== 'createTime' && res.prop !== 'appCode') {
        //     res.disabled = !data.editable
        //   }
        //   return res.disabled
        // })
        this.dealIsHideItem(false)
        appListApi.sysAppDetail({ appId: data.appId }).then((response) => {
          // this.config.formData = res.data
          const { appIcon, ...res } = response.data
          const temp = res.iconType == 1 ? (appIcon
            ? [{ fileId: appIcon, url: `${process.env.VUE_APP_BASE_API + cloud.file}/sysFileInfo/private/preview?fileId=${appIcon}&token=${this.$store.getters.token}`, name: '' }]
            : []) : appIcon
          this.config.formData = {
            ...res,
            appIcon: temp
          }
        })
      } else {
        this.config.formData.appCode = uuId(8)
        if (this.config.listTypeInfo.typeList && this.config.listTypeInfo.typeList.length > 0) {
          this.config.formData.appType = this.config.listTypeInfo.typeList[0].id
        }
        this.config.columns[1].disabled = false
        this.isDisabled = false
        this.dealIsHideItem(true)
      }
    },
    dealIsHideItem(status) {
      this.config.columns = this.config.columns.map((res) => {
        if (res.prop == 'createUser' || res.prop == 'createTime' || res.prop == 'maintainer') {
          res.isHideItem = status
        }
        return res
      })
    },
    // 创建请求
    onSubmit() {
      this.config.ref.validate(async (valid) => {
        if (valid) {
          const { appIcon } = this.config.formData
          const param = {
            appIcon: Array.isArray(appIcon) ? appIcon[0].fileId : appIcon,
            iconType: Array.isArray(appIcon) ? '1' : '2' // 1自定义图片，2图标
          }
          const fn = this.config.formData.appId != null ? appListApi.sysAppEdit : appListApi.sysAppAdd
          const mes = this.config.formData.appId != null ? '设置' : '新增'
          fn({ ...this.config.formData, ...param }).then((response) => {
            this.$dtModal.msgSuccess(`${mes}成功`)
            this.dialogFormVisible = false
            this.$parent.getList()
            if (!this.config.formData.appId) { // 新增
              const { appCode, appName, appId, statusFlag } = response.data
              const routeUrl = this.$router.resolve({
                path: '/designerTemplate',
                query: {
                  appCode, appName, appId, statusFlag
                }
              })
              window.open(routeUrl.href, '_blank')
            }
            this.reset()
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.leftRadio{
border-right: 1px solid #606266;
padding-right: 12px;
}
::v-deep .el-tabs__nav-wrap::after {
  height: 200px !important;
  display: flex;
  justify-content: center;
}
</style>
